<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主体内容 -->
    <div class="flex min-h-screen">
      <!-- 右侧内容 -->
      <div class="w-full p-6">
        <!-- 顶部标题和操作区 -->
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-medium">项目申请</h2>
          <el-button type="primary" class="!rounded-button" @click="handleAdd">
            <el-ico n class="mr-1"><Plus /></el-ico>
            新建项目申请
          </el-button>
        </div>

        <!-- 搜索和筛选区 -->
        <div class="bg-white p-6 rounded-lg shadow-sm mb-6">
          <div class="grid grid-cols-4 gap-6">
            <el-input
              v-model="queryParams.title"
              placeholder="搜索项目名称"
              class="w-full"
              :prefix-icon="Search"
            />
            <el-select
              v-model="queryParams.status"
              placeholder="申请状态"
              class="w-full"
            >
              <el-option label="全部状态" value="" />
              <el-option label="申请中" value="申请中" />
              <el-option label="评审中" value="评审中" />
              <el-option label="执行中" value="执行中" />
              <el-option label="验收中" value="验收中" />
              <el-option label="完成" value="完成" />
              <el-option label="驳回" value="驳回" />
            </el-select>
            <el-select
              v-model="queryParams.applyDate"
              placeholder="申请年份"
              class="w-full"
            >
              <el-option label="全部年份" value="" />
              <el-option label="2026 年" value="2026-01-01" />
              <el-option label="2025 年" value="2025-01-01" />
              <el-option label="2024 年" value="2024-01-01" />
              <el-option label="2023 年" value="2023-01-01" />
            </el-select>
            <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              @click="handleQuery"
            >
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </div>
        </div>

        <!-- 项目列表 -->
        <div class="bg-white rounded-lg shadow-sm">
          <el-table :data="projectsList" style="width: 100%">
            <el-table-column prop="id" label="项目编号" width="120" />
            <el-table-column prop="title" label="项目名称" min-width="200">
              <template #default="{ row }">
                <div class="flex items-center">
                  <span>{{ row.title }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="applicantName" label="申请人" width="120" />
            <el-table-column prop="budget" label="申请经费" width="120">
              <template #default="{ row }"> {{ row.budget }} 万元 </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.status === '申请中'
                      ? 'info'
                      : row.status === '评审中'
                      ? 'primary'
                      : row.status === '执行中'
                      ? 'primary'
                      : row.status === '验收中'
                      ? 'info'
                      : row.status === '完成'
                      ? 'success'
                      : row.status === '驳回'
                      ? 'danger'
                      : 'info'
                  "
                >
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="applyDate" label="申请时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <div class="flex space-x-2">
                  <el-button type="primary" link @click="handleView(row)"
                    >查看</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    @click="handleUpdate(row)"
                    :disabled="row.status !== '申请中' && row.status !== '驳回'"
                    >编辑</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    @click="submitProject(row)"
                    :disabled="row.status !== '申请中' && row.status !== '驳回'"
                    >提交</el-button
                  >
                  <el-button
                    type="danger"
                    link
                    @click="handleDelete(row)"
                    :disabled="row.status !== '申请中'"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex justify-end p-4">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes, prev, pager, next"
            />
          </div>
        </div>

        <!-- 新建项目对话框 -->
        <el-dialog v-model="open" title="新建项目申请" width="800px">
          <el-form :model="form" label-width="120px">
            <el-form-item label="项目名称" required>
              <el-input
                v-model="form.title"
                :disabled="ifView"
                placeholder="请输入项目名称"
              />
            </el-form-item>
            <!-- <el-form-item label="项目申请人" required>
              <el-select v-model="form.applicationName" placeholder="请选择项目申请人" class="w-full">
              <el-option label="全部状态" value="" />
              <el-option label="申请中" value="申请中" />
              <el-option label="评审中" value="评审中" />
              <el-option label="通过" value="通过" />
              <el-option label="执行中" value="执行中" />
              <el-option label="验收中" value="验收中" />
              <el-option label="完成" value="完成" />
              <el-option label="驳回" value="驳回" />
            </el-select>
            </el-form-item> -->
            <el-form-item label="申请经费/万" required>
              <el-input-number
                v-model="form.budget"
                :min="1"
                :max="1000"
                class="w-full"
                :disabled="ifView"
              />
            </el-form-item>
            <el-form-item label="项目概述" required>
              <el-input
                v-model="form.description"
                :disabled="ifView"
                type="textarea"
                rows="4"
                placeholder="请输入项目概述"
              />
            </el-form-item>
            <el-form-item label="开始时间" required>
              <el-date-picker
                v-model="form.startDate"
                type="date"
                :disabled="ifView"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="交付时间" required>
              <el-date-picker
                v-model="form.deadline"
                type="date"
                :disabled="ifView"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="研究计划">
              <!-- 上传文件 -->
              <file-upload
                :fileSize="10"
                :limit="1"
                v-model="form.applicationFile"
                :disabled="ifView"
                :handleFileClick="handleClickFile"
              ></file-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="cancel">取消</el-button>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="submitForm"
              >
                保存
              </el-button>
            </span>
          </template>
        </el-dialog>

        <el-dialog
          title="研究计划文档"
          v-model="docDialogVisible"
          width="80%"
          append-to-body
          destroy-on-close
        >
          <div class="w-full overflow-auto">
            <vue-office-docx
              v-if="previewType === 'docx' || previewType === 'doc'"
              :src="src"
            />
            <vue-office-pdf v-if="previewType === 'pdf'" :src="src" />
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<!-- <script lang="ts" setup>
import { ref, onMounted } from "vue"
import {
  listProjects,
  getProjects,
  addProjects,
  updateProjects,
  delProjects,
} from "@/api/project/application.js"
import {
  Bell,
  DataLine,
  Document,
  Loading,
  Check,
  Plus,
  Search,
  Upload,
} from "@element-plus/icons-vue"
const activeMenu = ref("2")
// 搜索和筛选
const searchKeyword = ref("")
const statusFilter = ref("")
const typeFilter = ref("")
const yearFilter = ref("")

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 新建项目对话框
const showNewProjectDialog = ref(false)
const newProject = ref({
  name: "",
  type: "",
  department: "",
  leader: "",
  amount: 100,
  description: "",
})

// 项目列表数据
const projectList = ref([
  {
    id: "PRJ202401001",
    name: "新一代量子通信技术研究与应用",
    type: "key",
    typeText: "重点项目",
    leader: "王智慧",
    department: "量子信息研究所",
    amount: 500,
    status: "reviewing",
    statusText: "审核中",
    createTime: "2024-01-15 14:30:00",
  },
  {
    id: "PRJ202401002",
    name: "碳基纳米材料在储能领域的应用研究",
    type: "general",
    typeText: "面上项目",
    leader: "李明远",
    department: "材料科学与工程学院",
    amount: 200,
    status: "approved",
    statusText: "已通过",
    createTime: "2024-01-12 09:15:00",
  },
  {
    id: "PRJ202401003",
    name: "基于深度学习的医疗影像智能诊断系统",
    type: "youth",
    typeText: "青年项目",
    leader: "张雪莲",
    department: "人工智能研究中心",
    amount: 150,
    status: "draft",
    statusText: "待提交",
    createTime: "2024-01-10 16:45:00",
  },
  {
    id: "PRJ202401004",
    name: "城市大气污染物协同治理关键技术研究",
    type: "general",
    typeText: "面上项目",
    leader: "陈海洋",
    department: "环境科学与工程学院",
    amount: 180,
    status: "rejected",
    statusText: "已拒绝",
    createTime: "2024-01-08 11:20:00",
  },
  {
    id: "PRJ202401005",
    name: "新型光电材料的设计与性能优化",
    type: "key",
    typeText: "重点项目",
    leader: "郑光明",
    department: "物理研究所",
    amount: 450,
    status: "reviewing",
    statusText: "审核中",
    createTime: "2024-01-05 15:40:00",
  },
])

// 操作方法
const viewProject = (row: any) => {
  console.log("查看项目", row)
}

const editProject = (row: any) => {
  console.log("编辑项目", row)
}

const submitProject = (row: any) => {
  console.log("提交项目", row)
}

const deleteProject = (row: any) => {
  console.log("删除项目", row)
}

const submitNewProject = () => {
  console.log("提交新项目", newProject.value)
  showNewProjectDialog.value = false
}
onMounted(() => {
  // 页面加载完成后的初始化操作
})

const getList = () => {
  listProjects({}).then((response) => {
    projectsList = response.rows
    total = response.total
  })
}
</script> -->

<script setup name="Application">
import {
  listProjects,
  getProjects,
  delProjects,
  addProjects,
  updateProjects,
  submit,
} from "@/api/project/application.js"
import VueOfficeDocx from "@vue-office/docx"
import VueOfficePdf from "@vue-office/pdf"

const { proxy } = getCurrentInstance()
const projectsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const ifView = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applicantId: null,
    title: null,
    description: null,
    applicationFile: null,
    demonstrationFile: null,
    applyDate: null,
    status: null,
    startDate: null,
    deadline: null,
    budget: null,
    createdAt: null,
    updatedAt: null,
  },
  rules: {
    applicantId: [
      { required: true, message: "申请人ID不能为空", trigger: "blur" },
    ],
    title: [{ required: true, message: "项目标题不能为空", trigger: "blur" }],
    applyDate: [
      { required: true, message: "申请时间不能为空", trigger: "blur" },
    ],
    status: [
      { required: true, message: "项目状态不能为空", trigger: "change" },
    ],
    createdAt: [
      { required: true, message: "记录创建时间不能为空", trigger: "blur" },
    ],
    updatedAt: [
      { required: true, message: "记录更新时间不能为空", trigger: "blur" },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询项目基本信息列表 */
function getList() {
  loading.value = true
  listProjects(queryParams.value).then((response) => {
    projectsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  getList()
}

/** 页码改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
  ifView.value = false
  reset()
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    applicantId: null,
    title: null,
    description: null,
    applicationFile: null,
    demonstrationFile: null,
    applyDate: null,
    status: null,
    startDate: null,
    deadline: null,
    budget: null,
    createdAt: null,
    updatedAt: null,
  }
  proxy.resetForm("projectsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  console.log(11)
  reset()
  open.value = true
  title.value = "添加项目基本信息"
}

function handleView(row) {
  reset()
  const _id = row.id || ids.value
  getProjects(_id).then((response) => {
    form.value = response.data
    open.value = true
    ifView.value = true
    title.value = "查看项目基本信息"
  })
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getProjects(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = "修改项目基本信息"
  })
}

/** 提交按钮 */
function submitForm() {
  if (form.value.id != null) {
    updateProjects(form.value).then((response) => {
      proxy.$modal.msgSuccess("修改成功")
      open.value = false
      getList()
    })
  } else {
    addProjects(form.value).then((response) => {
      proxy.$modal.msgSuccess("新增成功")
      open.value = false
      getList()
    })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除项目基本信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delProjects(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => {})
}

// 提交项目
const submitProject = (row) => {
  submit(row).then((res) => {
    // 弹出成功提示
    proxy.$modal.msgSuccess("提交成功")
    // 刷新列表
    getList()
  })
}

const previewType = ref("")
const src = ref("")
const docDialogVisible = ref(false)
const getFileExtension = (filename) => {
  return filename
    .slice(((filename.lastIndexOf(".") - 1) >>> 0) + 2)
    .toLowerCase()
}
function handleViewFile(url) {
  if (url) {
    fetch(url)
      .then((response) => {
        if (!response.ok) throw new Error("Network response was not ok")
        previewType.value = getFileExtension(url)
        return response.arrayBuffer()
      })
      .then((arrayBuffer) => {
        src.value = arrayBuffer // 将文件内容赋值给src，vue-office-docx组件会自动渲染
        docDialogVisible.value = true // 显示文档对话框
      })
      .catch((error) => {
        console.error("Failed to fetch the document:", error)
      })
  }
}

const handleClickFile = (url) => {
  console.log(url)
  handleViewFile(url)
}

getList()
</script>

<style scoped>
.el-menu {
  border-right: none;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 11px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}
</style>